package com.linln.common.utils;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.linln.common.vo.WechatLogin;
import java.util.Objects;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Title: timo
 * @Package: com.linln.common.utils
 * @ClassName: WechatUtil
 * @Description: TODO
 * @Author: Viceroy
 * @Date: 2022/4/13 9:15 PM
 */
public class WechatUtil {

  @Autowired
  WxMaService wxMaService;

  /**
   * 获取用户登录Session
   */
  public WxMaJscode2SessionResult getWechatSession(WechatLogin wechatLogin) {
    WxMaJscode2SessionResult session = null;
    try {
      // 获取微信用户session
      session = wxMaService.getUserService().getSessionInfo(wechatLogin.getCode());
      if (null == session) {
        throw new RuntimeException("登录异常");
      }
    } catch (WxErrorException e) {
      throw new RuntimeException("获取微信用户Session异常");
    }

    return session;
  }


  /**
   * 解密微信用户信息
   */
  public WxMaUserInfo getWxMaUserInfo(WxMaJscode2SessionResult wxMaJscode2SessionResult, WechatLogin wechatLogin) {
    WxMaUserInfo wxUserInfo = wxMaService.getUserService().getUserInfo(wxMaJscode2SessionResult.getSessionKey(),
        wechatLogin.getBasicEncryptedData(), wechatLogin.getBasicIv());
    if (null == wxUserInfo) {
      throw new RuntimeException("获取用户信息异常");
    }

    return wxUserInfo;
  }

  /**
   * 解密手机号码信息
   */
  public WxMaPhoneNumberInfo getWxMaPhoneNumberInfo(WxMaJscode2SessionResult wxMaJscode2SessionResult, WechatLogin wechatLogin) {
    WxMaPhoneNumberInfo wxMaPhoneNumberInfo = wxMaService.getUserService().getPhoneNoInfo(wxMaJscode2SessionResult.getSessionKey(),wechatLogin.getPhoneEncryptedData(), wechatLogin.getPhoneIv());
    if (Objects.isNull(wxMaPhoneNumberInfo) || StringUtils.isBlank(wxMaPhoneNumberInfo.getPhoneNumber())) {
      throw new RuntimeException("解密手机号码信息错误");
    }

    return wxMaPhoneNumberInfo;
  }
}
